import axios from "axios";
import config from "../config";

export function login(username, password) {
  const params = new URLSearchParams();
  params.append("username", username);
  params.append("password", password);
  // 打印出拼接后的 URL
  const fullURL = `${config.baseURL}/login`;
  console.log("Request URL:", fullURL);
  // 发送请求
  return axios.post(fullURL,
    {
      username: username,
      password: password
    },
    {
      headers: {
          'Content-Type': 'application/json'
      }
  }
  );
}

export function saveToken(token, username) {
  localStorage.setItem("token", token);
  localStorage.setItem("username", username);
}

export function getToken() {
  return localStorage.getItem("token");
}

export function removeToken() {
  localStorage.removeItem("token");
}

export function getRole() {
  try {
    const token = getToken();
    if (!token) {
      console.warn('Token 不存在');
      return null;
    }
    // Base64 解码整个 token
    const decodedString = atob(token);
    // 移除 SECRET_KEY
    const jsonString = decodedString.replace('mySecretKey', '');
    // 解析 JSON
    const payload = JSON.parse(jsonString);
    return payload.role;
  } catch (error) {
    console.error('Token 解析失败:', error);
    return null;
  }
}

// 获取完整的 token 信息
export function getTokenInfo() {
  try {
    const token = getToken();
    if (!token) {
      return null;
    }
    const decodedString = atob(token);
    const jsonString = decodedString.replace('mySecretKey', '');
    return JSON.parse(jsonString);
  } catch (error) {
    console.error('Token 解析失败:', error);
    return null;
  }
}

// 检查 token 是否有效
export function isTokenValid() {
  try {
    const tokenInfo = getTokenInfo();
    if (!tokenInfo) {
      return false;
    }
    return new Date().getTime() <= tokenInfo.expiry;
  } catch (error) {
    return false;
  }
}

// 获取用户ID
export function getUserId() {
  const tokenInfo = getTokenInfo();
  return tokenInfo?.userId;
}

// 获取用户名
export function getUsername() {
  const tokenInfo = getTokenInfo();
  console.log('tokenInfo', tokenInfo.username);
  return tokenInfo.username;
}

// 获取用户头像
export const getUserAvatar = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  let avatar = userInfo.avatar || '';
  if (avatar && avatar.startsWith('https://')) {
    avatar = 'http://' + avatar.substring(8);
  }
  return avatar;
};
